// 获取DOM元素
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const messagesList = document.getElementById('messages');
const chatMessages = document.querySelector(".chat-messages")
// 用户头像
const userAvatar = "./img/dog.avif"
const username = "张三"
// chatgpt 头像
const chatgptAvatar = "./img/chatgpt.avif"
const chatBotName = "chatgpt"



const ajax = function(url,data){
  return new Promise((resolve,reject) =>{
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
        resolve(xhr.responseText)
      }
    };

    xhr.onerror = function(){
      reject()
    }
    xhr.send(JSON.stringify(data));
  })
}

const chatapi = "https://84ihhn38v9.hk.aircode.run/chat"

// 发送消息
async function sendMessage() {
  const message = messageInput.value;
  if (message.trim() !== '') {
    const li = document.createElement('li');
    li.innerHTML = `
      <img class="avatar" src="${userAvatar}" alt="Avatar">
      <div>
        <div class="name">${username}</div>
        <div class="message sent">${message}</div>
      </div>
    `;
    messagesList.appendChild(li);
    messageInput.value = '';
    chatMessages.scrollTop = messagesList.scrollHeight ;


    let response = await ajax(chatapi,{message})
    console.log(response)
    let json = JSON.parse(response)
    console.log(json)
    receiveMessage(json.response.content)
  }
}


// 接收消息
function receiveMessage(message) {
  const li = document.createElement('li');
  li.innerHTML = `
    <img class="avatar" src="${chatgptAvatar}" alt="Avatar">
    <div>
      <div class="name">${chatBotName}</div>
      <div class="message received">${message}</div>
    </div>
  `;
  messagesList.appendChild(li);
  chatMessages.scrollTop = messagesList.scrollHeight;
}

// 监听发送按钮点击事件
sendButton.addEventListener('click', sendMessage);

// 监听回车键按下事件
messageInput.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    sendMessage();
  }
});


// 模拟接收消息
// setInterval(receiveMessage, 1000);